package com.pine.dbant.core.service;

import com.github.sd4324530.jtuple.Tuple2;
import com.pine.dbant.common.exeception.BusinessException;
import com.pine.dbant.common.plugin.DatabasePlugin;
import com.pine.dbant.common.plugin.PluginFactory;
import com.pine.dbant.core.entity.Connection;
import com.pine.sunflower.core.utils.Strings;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author xiaoyuan
 * @create 2022/11/30 10:21
 **/
public class BasePluginService {
    @Autowired
    protected ConnectionService connectionService;
    @Autowired
    protected PluginFactory pluginFactory;

    public Tuple2<Connection,DatabasePlugin> buildDatabasePlugin(Long connId) {
        Connection connection = connectionService.getById(connId);
        if (connection == null) {
            throw new BusinessException("连接信息不存在");
        }
        String pluginId = connection.getDsType();
        DatabasePlugin databasePlugin = (DatabasePlugin) pluginFactory.getPlugin(pluginId);
        if (databasePlugin == null) {
            throw new BusinessException(Strings.format("该插件[{}]未实现或未安装", pluginId));
        }
        return Tuple2.with(connection,databasePlugin);
    }
    public Tuple2<Connection,DatabasePlugin> buildDatabasePlugin(String pluginId,Long connId) {
        Connection connection = connectionService.getById(connId);
        if (connection == null) {
            throw new BusinessException("连接信息不存在");
        }
        if(StringUtils.isBlank(pluginId)){
            pluginId = connection.getDsType();
        }
        DatabasePlugin databasePlugin = (DatabasePlugin) pluginFactory.getPlugin(pluginId);
        if (databasePlugin == null) {
            throw new BusinessException(Strings.format("该插件[{}]未实现或未安装", pluginId));
        }
        return Tuple2.with(connection,databasePlugin);
    }
}
